package com.senlingspace.system.service.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

import com.alibaba.fastjson2.JSON;
import com.senlingspace.common.enums.UserType;
import com.senlingspace.common.utils.*;
import com.senlingspace.system.domain.SlkjProductAttribute;
import com.senlingspace.system.domain.SlkjShopProduct;
import com.senlingspace.system.domain.dto.ShopProductDto;
import com.senlingspace.system.domain.vo.SlkjProductVO;
import com.senlingspace.system.mapper.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.senlingspace.system.domain.SlkjProduct;
import com.senlingspace.system.service.ISlkjProductService;
import org.springframework.transaction.annotation.Transactional;

/**
 * 商品管理Service业务层处理
 *
 * @author wangliang
 * @date 2024-07-30
 */
@Service
@Slf4j
public class SlkjProductServiceImpl implements ISlkjProductService {
    @Autowired
    private SlkjProductMapper slkjProductMapper;
    @Autowired
    private SlkjShopProductMapper shopProductMapper;
    @Autowired
    private SlkjProductAttributeMapper productAttributeMapper;
    @Autowired
    private SlkjShoppingCartMapper slkjShoppingCartMapper;


    /**
     * 查询商品管理
     *
     * @param productId 商品管理主键
     * @return 商品管理
     */
    @Override
    public SlkjProductVO selectSlkjProductByProductId(Long productId) {
        SlkjProduct product = slkjProductMapper.selectSlkjProductByProductId(productId);
        List<SlkjProductAttribute> productAttributes = productAttributeMapper.selectSlkjProductAttributeByProductId(product.getProductId());
        SlkjProductVO vo = new SlkjProductVO();
        vo.setProductAttributes(productAttributes);
        BeanUtils.copyProperties(product, vo);

        Long price = product.getPrice();
        if (Objects.nonNull(price)) {
            vo.setPrice(MoneyUtils.fen2Yuan(price));
        }

        Long principal = product.getPrincipal();
        if (Objects.nonNull(principal)) {
            vo.setPrincipal(MoneyUtils.fen2Yuan(principal));
        }
        return vo;
    }

    /**
     * 查询商品管理列表
     *
     * @param slkjProduct 商品管理
     * @return 商品管理
     */
    @Override
    public List<SlkjProductVO> selectSlkjProductList(SlkjProduct slkjProduct, Long shopId) {
        PageUtils.startPage();
        if (UserType.SHOP.getCode().equals(SecurityUtils.getHeadquarters()) || shopId != null) {
            if (shopId == null) {
                return new ArrayList<>();
            }
            log.info("当前为门店账号:{}", shopId);
            slkjProduct.setDelFlag("0");
            slkjProduct.setStatus("0");

            List<SlkjProductVO> productShopList = slkjProductMapper.selectSlkjProductList(slkjProduct);
            log.info("总部上架商品信息，{}", productShopList);
            for (int i = 0; i < productShopList.size(); i++) {
                // 如果没有该商品 ，设置状态为未上架
                int productNum = shopProductMapper.selectShopProductByProId(shopId, productShopList.get(i).getProductId());
                if (productNum == 0) {
                    productShopList.get(i).setStatus("1");
                } else {
                    productShopList.get(i).setStatus("0");
                }
                // 隐藏成本价
                productShopList.get(i).setPrincipal(null);

                // 分转为元
                String price = productShopList.get(i).getPrice();
                if (StringUtils.isNotEmpty(price)) {
                    productShopList.get(i).setPrice(MoneyUtils.fen2Yuan(Long.parseLong(price)));
                }
            }

            log.info("当前门店商品数据，{}", JSON.toJSONString(productShopList));
            return productShopList;
        }

        List<SlkjProductVO> slkjProductVOS = slkjProductMapper.selectSlkjProductList(slkjProduct);
        for (SlkjProductVO productVO : slkjProductVOS) {
            String principal = productVO.getPrincipal();
            if (StringUtils.isNotEmpty(principal)) {
                productVO.setPrincipal(MoneyUtils.fen2Yuan(Long.parseLong(principal)));
            }

            String price = productVO.getPrice();
            if (StringUtils.isNotEmpty(price)) {
                productVO.setPrice(MoneyUtils.fen2Yuan(Long.parseLong(price)));
            }
        }
        return slkjProductVOS;
    }

    /**
     * 新增商品管理
     *
     * @param slkjProduct 商品管理
     * @return 结果
     */
    @Override
    @Transactional
    public int insertSlkjProduct(SlkjProductVO slkjProduct) throws IllegalArgumentException {
        SlkjProduct product = new SlkjProduct();
        BeanUtils.copyProperties(slkjProduct, product);
        product.setCreateTime(DateUtils.getNowDate());
        product.setCreateBy(SecurityUtils.getUsername());

        String price = slkjProduct.getPrice();
        if (StringUtils.isNotEmpty(price)) {
            product.setPrice((long) MoneyUtils.yuan2Fen(price));
        } else {
            throw new IllegalArgumentException("商品售卖价格不可为空");
        }

        String principal = slkjProduct.getPrincipal();
        if (StringUtils.isNotEmpty(principal)) {
            product.setPrincipal((long) MoneyUtils.yuan2Fen(principal));
        } else {
            throw new IllegalArgumentException("商品进货价不可为空");
        }

        if (product.getPrice() < product.getPrincipal()) {
            throw new IllegalArgumentException("商品进货价不可大于商品售卖价格");
        }

        slkjProductMapper.insertSlkjProduct(product);

        for (SlkjProductAttribute productAttribute : slkjProduct.getProductAttributes()) {
            productAttribute.setCreateBy(SecurityUtils.getUsername());
            productAttribute.setCreateTime(DateUtils.getNowDate());
            productAttribute.setProductId(product.getProductId());
            productAttributeMapper.insertSlkjProductAttribute(productAttribute);
        }

        StringBuffer productNumber = new StringBuffer();
        // 将shopId转换为字符串，长度不足3位则在前面补充0
        String productTpyeIdStr = String.format("%04d", product.getProductTpyeId());
        productNumber.append(productTpyeIdStr);
        String productIdStr = String.format("%08d", product.getProductId());
        productNumber.append(productIdStr);
        product.setProductNumber(productNumber.toString());
        return slkjProductMapper.updateSlkjProduct(product);
    }

    /**
     * 修改商品管理
     *
     * @param slkjProduct 商品管理
     * @return 结果
     */
    @Override
    public int updateSlkjProduct(SlkjProductVO slkjProduct) throws IllegalArgumentException {
        SlkjProduct product = new SlkjProduct();
        BeanUtils.copyProperties(slkjProduct, product);
        product.setUpdateTime(DateUtils.getNowDate());
        product.setUpdateBy(SecurityUtils.getUsername());

        String price = slkjProduct.getPrice();
        if (StringUtils.isNotEmpty(price)) {
            product.setPrice((long) MoneyUtils.yuan2Fen(price));
        } else {
            throw new IllegalArgumentException("商品售卖价格不可为空");
        }

        String principal = slkjProduct.getPrincipal();
        if (StringUtils.isNotEmpty(principal)) {
            product.setPrincipal((long) MoneyUtils.yuan2Fen(principal));
        } else {
            throw new IllegalArgumentException("商品进货价不可为空");
        }

        if (product.getPrice() < product.getPrincipal()) {
            throw new IllegalArgumentException("商品进货价不可大于商品售卖价格");
        }

        productAttributeMapper.updateSlkjProductAttributeByProductId(slkjProduct.getProductId());

        if(slkjProduct.getProductAttributes().size() > 0){
            for (SlkjProductAttribute productAttribute : slkjProduct.getProductAttributes()) {
                if ("".equals(productAttribute.getId()) || null == productAttribute.getId()) {
                    productAttribute.setCreateBy(SecurityUtils.getUsername());
                    productAttribute.setCreateTime(DateUtils.getNowDate());
                    productAttribute.setProductId(slkjProduct.getProductId());
                    productAttributeMapper.insertSlkjProductAttribute(productAttribute);
                } else {
                    productAttribute.setUpdateBy(SecurityUtils.getUsername());
                    productAttribute.setUpdateTime(DateUtils.getNowDate());
                    productAttribute.setProductId(slkjProduct.getProductId());
                    productAttributeMapper.updateSlkjProductAttribute(productAttribute);
                }
            }
        }
        return slkjProductMapper.updateSlkjProduct(product);
    }

    @Override
    public int deleteSlkjProductByProductIds(Long[] productIds) {
        return slkjProductMapper.deleteSlkjProductByProductIds(productIds);
    }

    /**
     * 删除商品管理信息
     *
     * @param productId 商品管理主键
     * @return 结果
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public int deleteSlkjProductByProductId(Long productId) {

        SlkjProduct product = slkjProductMapper.selectSlkjProductByProductId(productId);
        product.setDelFlag("1");
        product.setUpdateBy(SecurityUtils.getUsername());
        product.setUpdateTime(DateUtils.getNowDate());
        int count = slkjProductMapper.updateSlkjProduct(product);

        if (count == 1) {
            long deleted = slkjShoppingCartMapper.deleteCartByProductId(productId);
            log.info("删除购物车中商品 [{}], 共删除：{}", productId, deleted);
        }

        return count;
    }

    @Override
    public int updateShopProductStatus(ShopProductDto shopProductDto) {
        {
            SlkjProduct product = slkjProductMapper.selectSlkjProductByProductId(shopProductDto.getProductId());
            Long shopId = shopProductDto.getShopId();


            if (shopId != null && shopId != 1L) {
                log.info("门店账号修改商品状态");

                if ("1".equals(shopProductDto.getStatus())) {
                    return shopProductMapper.deleteShopProductByPorductIdShopId(shopId, shopProductDto.getProductId());
                } else {
                    SlkjShopProduct shopProduct = new SlkjShopProduct();
                    shopProduct.setProductId(shopProductDto.getProductId());
                    shopProduct.setShopId(shopId);
                    shopProduct.setProductStatus("0");
                    int proShopSatuNum = shopProductMapper.selectShopProductByProId(shopId, shopProductDto.getProductId());
                    if (proShopSatuNum == 0) {
                        return shopProductMapper.insertSlkjShopProduct(shopProduct);
                    }
                    return proShopSatuNum;
                }

            } else if (UserType.OPERATE.getCode().equals(SecurityUtils.getHeadquarters()) || UserType.SYSTEM.getCode().equals(SecurityUtils.getHeadquarters())) {
                log.info("总部账号修改商品状态");
                product.setUpdateTime(DateUtils.getNowDate());
                product.setUpdateBy(SecurityUtils.getUsername());
                product.setStatus(shopProductDto.getStatus());
                return slkjProductMapper.updateSlkjProduct(product);
            }
            return 0;
        }
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public int updateAppStatus(String appStatus, Long productId) {
        int updated = slkjProductMapper.updateAppProduct(appStatus, productId);
        if (updated == 1) {
            log.info("商品 [{}] 状态修改为：{}", productId, appStatus);
            long count = slkjShoppingCartMapper.updateGoodsExpireByProductId(Byte.valueOf(appStatus), productId);
            log.info("商品 [{}] 购物车状态修改为：{}，共修改 {} 条", productId, appStatus, count);
        }
        return updated;
    }

}
